import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { ActionSheet, Toast, Skeleton, ImagePreview } from 'react-vant'
import {
  Play,
  Exchange,
  ChatO,
  GoodJobO,
  Ellipsis,
  Passed
} from '@react-vant/icons'
import './index.less'

import { toDate, numValue } from '@/util/index'

const actions = [{ name: '复制链接' }, { name: '分享' }]

const Index = props => {
  const { cards, state, text,url } = props
  const Navigate = useNavigate()

  const [more, setMore] = useState(false)

  const showHtml = htmlStr => {
    let html = { __html: htmlStr }
    return <div className="weibo-text" dangerouslySetInnerHTML={html}></div>
  }

  const [cardIndex, setIndex] = useState(0)

  const showMenu = () => {
    setMore(!more)
  }

  const cardShow = (e, index) => {
    e.stopPropagation()
    setIndex(index)
    showMenu()
  }

  // 操作 分享
  const Select = (action, index, cards) => {
    let linkStr = `https://weibo.com/${cards.mblog.user.id}/${cards.mblog.bid}`
    if (index === 0) {
      copyLink(linkStr)
    } else {
      navigator.share({
        //要共享的标题
        title: window.location.title,
        //要共享的 URL
        url: linkStr,
        //要共享的文本
        text: ''
      })
      Toast({
        message: '分享成功',
        icon: <Passed />
      })
    }
    setMore(!more)
  }

  // 删除预览图生成的DOM节点
  const imgClose = () => {
    let dom = document.querySelectorAll('.rv-image-preview')
    dom.forEach(item => {
      let node = item.parentNode
      node.remove()
    })
  }

  // 微博类型
  const wbMain = itemType => {
    if (itemType.mblog.page_info && itemType.mblog.page_info.type === 'video') {
      /* 视频 */
      return (
        <div className="weibo-media f-media">
          <div className="weibo-media-wraps">
            <div className="card-video type-video vertical">
              <div className="mwb-video mwbv-play mwbv-info">
                <div className="m-img-box">
                  <img src={itemType.mblog.page_info.page_pic.url} alt="" />
                </div>
                <button className="mwbv-play-button">
                  <Play />
                </button>
                <div className="mwbv-info-bar">
                  <div className="m-box">
                    <div className="m-box-col">
                      {' '}
                      {itemType.mblog.page_info.play_count}{' '}
                    </div>
                    <div className="time">
                      {itemType.mblog.page_info.media_info.duration}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )
    } else if (itemType.mblog.pics && itemType.mblog.pics.length > 0) {
      // 图文
      return (
        <>
          <div className="weibo-media-wraps weibo-media f-media media-b">
            <ul className="m-auto-list">
              {itemType.mblog.pics.map((item, idx) => {
                return (
                  <li
                    key={idx}
                    className={[
                      itemType.mblog.pics.length <= 2
                        ? 'm-auto-box2'
                        : 'm-auto-box3'
                    ]}
                  >
                    <div className="m-img-box m-imghold-4-3">
                      <img
                        onClick={e => imgPreview(e, itemType.mblog.pics, idx)}
                        className="f-bg-img"
                        src={item.url}
                      />
                    </div>
                  </li>
                )
              })}
            </ul>
          </div>
        </>
      )
    } else if (
      itemType.mblog.page_info &&
      itemType.mblog.page_info.type === 'live'
    ) {
      // 直播
      return (
        <div>
          <div className="weibo-media f-media">
            <div className="card-video type-video">
              <div className="mwb-video mwbv-play mwbv-info">
                <div className="m-img-box">
                  <img src={itemType.mblog.page_info.page_pic.url} />
                  <button className="mwbv-play-button">
                    <Play />
                  </button>
                  <div className="mwbv-info-bar"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )
    }
  }

  // 复制链接
  const copyLink = link => {
    const pEle = document.createElement('p')
    pEle.innerHTML = link || ''
    document.body.appendChild(pEle)

    const range = document.createRange() // 创造range
    window.getSelection().removeAllRanges() //清除页面中已有的selection
    range.selectNode(pEle) // 选中需要复制的节点
    window.getSelection().addRange(range)

    const copyStatus = document.execCommand('Copy') // 执行copy操作
    Toast({
      message: '复制成功',
      icon: <Passed />
    })
    document.body.removeChild(pEle)
    window.getSelection().removeAllRanges()
  }

  // 骨架屏
  const wbSkeleton = () => {
    let s = [...Array.from({ length: 10 }).keys()]
    return (
      <>
        {s.map((item, idx) => {
          return (
            <div key={idx} className="weibo-skeleton">
              <Skeleton
                avatar
                title
                row={5}
                round={false}
                rowHeight={10}
                rowWidth={['100%', '100%', '100%']}
              />
              <footer className="f-footer-ctrl">
                <div className="m-diy-btn m-box-center-a">
                  <Exchange className="lite-iconf lite-iconf-report" />
                  <h4>转发</h4>
                </div>
                <div className="m-diy-btn m-box-center-a">
                  <ChatO className="lite-iconf lite-iconf-comments" />
                  <h4>评论</h4>
                </div>
                <div className="m-diy-btn m-box-center-a">
                  <GoodJobO className="lite-iconf lite-iconf-like" />
                  <h4>赞</h4>
                </div>
                <aside onClick={() => cardShow(idx)}>
                  <Ellipsis />
                </aside>
              </footer>
            </div>
          )
        })}
      </>
    )
  }

  // 图片预览
  const imgPreview = (e, imgs, idx) => {
    e.stopPropagation()
    let images = []

    for (const iterator of imgs) {
      images.push(iterator.url)
    }

    ImagePreview.open({
      className: 'rest-preview',
      images,
      closeable: true,
      startPosition: idx,
      onClosed: () => imgClose()
    })
  }

  // 认证类型
  const verifiedType = user => {
    // -1 无认证 3 企业认证 0 个人认证
    if (
      user.verified &&
      user.verified_type === 0 &&
      user.verified_type_ext === 0
    ) {
      return <i className="m-icon m-icon-yellowv"></i>
    } else if (
      user.verified &&
      user.verified_type === 0 &&
      user.verified_type_ext === 1
    ) {
      return <i className="m-icon m-icon-goldv-static"></i>
    } else if (user.verified && user.verified_type === 1) {
    } else if (user.verified && user.verified_type === 2) {
    } else if (user.verified && user.verified_type === 3) {
      return <i className="m-icon m-icon-bluev"></i>
    } else {
      return
    }
  }

  // vip 级别
  const VipLevel = user => {
    if (user.mbrank > 0) {
      return (
        <i className={['m-icon', 'm-icon-vipl' + user.mbrank].join(' ')}></i>
      )
    }
  }

  // 微博详情
  const wbDetail = item => {
    // Navigate(`/detail/${item.mblog.id}`)
    Navigate(`/detail/${item.mblog.id}`, { state: { item } })
  }

  return (
    <div>
      {props.type == 'detali' ? (
        <div className="card m-panel card9 f-weibo">
          <div className="card-wrap">
            <header className="weibo-top m-box">
              <div className="m-avatar-box m-box-center">
                <a href="#" className="m-img-box">
                  <img src={state.item.mblog.user.avatar_hd} alt="头像" />
                  {verifiedType(state.item.mblog.user)}
                </a>
              </div>
              <div className="m-box-dir m-box-col m-box-center">
                <div className="m-text-box">
                  <a href="#">
                    <h3 className="m-text-cut">
                      {state.item.mblog.user.screen_name}
                      {VipLevel(state.item.mblog.user)}
                    </h3>
                  </a>
                  <h4 className="m-text-cut">
                    <span className="time">
                      {toDate(state.item.mblog.created_at)}
                    </span>
                    {state.item.mblog.source === '' ? (
                      <span> {state.item.mblog.region_name}</span>
                    ) : (
                      <span className="from">
                        {' '}
                        来自 {state.item.mblog.source}
                      </span>
                    )}
                    {state.item.mblog.edit_at ? (
                      <span className="time"> 已编辑</span>
                    ) : null}
                  </h4>
                </div>
              </div>
            </header>
          </div>
          <div className="weibo-main">
            <div className="card-wrap">
              <div className="weibo-og">
                <div className="weibo-text">{showHtml(text)}</div>
                <>{wbMain(state.item)}</>
              </div>
            </div>
          </div>
          <div className='wrap'>
            {url && <img src={url} alt="" />}
          </div>
        </div>
      ) : (
        cards.map((item, idx) => {
          return (
            <div key={idx}>
              <div onClick={() => wbDetail(item)} className="wb-item-wrap">
                <div className="wb-item">
                  <div className="card m-panel card9 f-weibo">
                    <div className="card-wrap">
                      <header className="weibo-top m-box">
                        <div className="m-avatar-box m-box-center">
                          <a href="#" className="m-img-box">
                            <img src={item.mblog.user.avatar_hd} alt="头像" />
                            {verifiedType(item.mblog.user)}
                          </a>
                        </div>
                        <div className="m-box-dir m-box-col m-box-center">
                          <div className="m-text-box">
                            <a href="#">
                              <h3 className="m-text-cut">
                                {item.mblog.user.screen_name}
                                {VipLevel(item.mblog.user)}
                              </h3>
                            </a>
                            <h4 className="m-text-cut">
                              <span className="time">
                                {toDate(item.mblog.created_at)}
                              </span>
                              {item.mblog.source === '' ? (
                                <span> {item.mblog.region_name}</span>
                              ) : (
                                <span className="from">
                                  {' '}
                                  来自 {item.mblog.source}
                                </span>
                              )}
                              {item.mblog.edit_at ? (
                                <span className="time"> 已编辑</span>
                              ) : null}
                            </h4>
                          </div>
                        </div>
                      </header>
                    </div>
                    <article className="weibo-main">
                      <div className="card-wrap">
                        <div className="weibo-og">
                          <>{showHtml(item.mblog.text)}</>
                          <>{wbMain(item)}</>
                        </div>
                      </div>
                    </article>
                    <footer className="f-footer-ctrl">
                      <div className="m-diy-btn m-box-center-a">
                        <Exchange className="lite-iconf lite-iconf-report" />
                        <h4>{numValue(item.mblog.reposts_count)}</h4>
                      </div>
                      <div className="m-diy-btn m-box-center-a">
                        <ChatO className="lite-iconf lite-iconf-comments" />
                        <h4>{item.mblog.comments_count}</h4>
                      </div>
                      <div className="m-diy-btn m-box-center-a">
                        <GoodJobO className="lite-iconf lite-iconf-like" />
                        <h4>{numValue(item.mblog.attitudes_count)}</h4>
                      </div>
                      <aside onClick={e => cardShow(e, idx)}>
                        <Ellipsis />
                      </aside>
                    </footer>
                  </div>
                </div>
              </div>
              {idx === cardIndex ? (
                <ActionSheet
                  round={false}
                  onSelect={(action, index) => Select(action, index, item)}
                  visible={more}
                  onCancel={() => showMenu()}
                  actions={actions}
                  cancelText="取消"
                />
              ) : null}
            </div>
          )
        })
      )}
    </div>
  )
}

export default Index
